/*
 	Copyright 2012 Christian Brosch
    This file is part of EasyGPSTracker.

    EasyGPSTracker is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    EasyGPSTracker is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with EasyGPSTracker.  If not, see <http://www.gnu.org/licenses/>.
 */

package broware.easygpstracker;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.util.Log;


public class EGTService extends Service {
	/*
	 * Service
	 */
	LocationManager lm;
	NotificationManager notMan;
	String mmsg="Bereit";
	String _action="auto";
	String _comm="";
	
    @Override
    public void onCreate(){
    	StrictMode.ThreadPolicy policy = new StrictMode.
    	ThreadPolicy.Builder().permitAll().build();
    	StrictMode.setThreadPolicy(policy);
    	lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    	notMan = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        super.onCreate();
        if(mgetPrefsBoolean("auto_update", false)) autoOn();
    }
    
    public IBinder onBind(Intent intent){Log.i("","Bind");return mBinder;}
    public int onStartCommand(Intent intent, int flags, int startId){return START_STICKY;}
    public void onDestroy(){
    	autoOff();
    }
	
	boolean _autoOn = false;
	
	private final IBinder mBinder = new LocalBinder();
	class LocalBinder extends Binder{
		EGTService getService(){
			return EGTService.this;
		}
	}
    /*
     * Einstellungen laden
     */
	
    public String mgetPrefs(String field){
    	SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    	return sharedPrefs.getString(field, "");
    }
    
    public boolean mgetPrefsBoolean(String field, boolean def){
    	SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    	return sharedPrefs.getBoolean(field, def);
    }
    
    /*
     * Auto-refresh
     */
    
    public void autoOn() {
    	_autoOn=true;
    	String time = mgetPrefs("set_intervall");
    	int i_time;
    	try{
    		i_time = Integer.decode(time);
    	} catch(NumberFormatException e){i_time=150;}
    	i_time = i_time*1000;
    	
    	String distance = mgetPrefs("set_distance");
    	int i_distance;
    	try{
    		i_distance = Integer.decode(distance);
    	} catch(NumberFormatException e){i_distance=200;}
    	
    	lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                i_time, // sek*1000
                i_distance,   // meter
                locationListener);
        info("Service gestartet");
        showNotification("GPS-Tracker gestartet");
    }
     
    public void autoOff(){
    	_autoOn=false;
    	lm.removeUpdates(locationListener);
    	info("Service gestoppt");
    	notMan.cancelAll();
    }
    
    
    
    public String mDate(){
    	SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.GERMAN);
        return sdf.format(new Date(System.currentTimeMillis()));
    }
    
    
    
    public void info(String msg){
    	mmsg=msg;
        if(_autoOn) showNotification(msg);
    }
    
    public void showNotification(String text){
    	Notification notification = new Notification(android.R.drawable.ic_menu_mylocation, text,System.currentTimeMillis());
    	notification.flags = Notification.FLAG_NO_CLEAR;
    	PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0,
		new Intent(getApplicationContext(),EGTActivity.class),
		PendingIntent.FLAG_UPDATE_CURRENT);
		notification.setLatestEventInfo(this, "EasyGPSTracker", text, contentIntent);
	    notMan.notify(0, notification);
    }    
    
	private final LocationListener locationListener = new LocationListener() {
	        public void onLocationChanged(Location l) {
	         upload(_action, _comm);
	         _comm="";
	         _action="auto";
	        }
	        public void onProviderDisabled(String provider){
	        	info("GPS deaktiviert");
	        }
	        public void onProviderEnabled(String provider) {
	        	info("GPS aktiviert");
	        }
	        public void onStatusChanged(String provider, int status, Bundle extras) {}        
	};
	
	
	
	public void manuelUpdate(String action, String comm){
		info("Update...");
		_action = action;
		_comm = comm;
		if(_autoOn){
			lm.removeUpdates(locationListener);
		    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                150000, // sek*1000
                200,   // meter
                locationListener);
		} else {
			lm.requestSingleUpdate("gps", locationListener, Looper.getMainLooper());
		}	
	}
	
	
	
	public void upload(String action, String comm){
		info("Letztes Update:"+mDate());
		Location l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		String user=mgetPrefs("set_user");
		String passwd=mgetPrefs("set_passwd");
		String url=mgetPrefs("set_url");
		String latitude = String.valueOf(l.getLatitude());
		String longitude = String.valueOf(l.getLongitude()); 
		String speed = String.valueOf(l.getSpeed());
		String bearing = String.valueOf(l.getBearing());
	    HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(url);
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("user", user));
	    nameValuePairs.add(new BasicNameValuePair("latitude", latitude));
	    nameValuePairs.add(new BasicNameValuePair("longitude", longitude));
	    nameValuePairs.add(new BasicNameValuePair("speed", speed));
	    nameValuePairs.add(new BasicNameValuePair("bearing", bearing));
	    nameValuePairs.add(new BasicNameValuePair("passwd", passwd));
	    nameValuePairs.add(new BasicNameValuePair("comm", comm));
	    nameValuePairs.add(new BasicNameValuePair("action", action));
	    try{
	    	httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	    	HttpResponse response = httpclient.execute(httppost);
	    }
	    catch(UnsupportedEncodingException e){}
	    catch(IOException e){
	    	info("Senden gescheitert");
	    }
	}
}